<template>
	<cl-page :padding="20">
		<view class="page">
			<cl-card label="录入信息">
				<cl-form ref="Form" v-model="form" :rules="rules" :disabled="loading" label-position="left">
					<cl-form-item prop="owner_name">
						<template #label><span class="required-icon">*</span>货主名称</template>
						<cl-input v-model="form.owner_name" placeholder="请填写货主名称" />
					</cl-form-item>

					<cl-form-item prop="plate_number">
						<template #label>车牌号</template>
						<cl-input v-model="form.plate_number" placeholder="请填写车牌号" />
					</cl-form-item>

					<cl-form-item prop="vehicle_model">
						<template #label>车牌型号</template>
						<cl-input v-model="form.vehicle_model" placeholder="请填写车牌型号" />
					</cl-form-item>

					<cl-form-item prop="driver_number">
						<template #label>司机号码</template>
						<cl-input v-model="form.driver_number" type="number" :maxlength="11" :minlength='11'
							placeholder="请填写司机号码" />
					</cl-form-item>

					<cl-form-item prop="goods">
						<template #label><span class="required-icon">*</span>货品信息</template>
						<cl-textarea v-model="form.goods" placeholder="请填写货品信息" />
					</cl-form-item>



					<cl-form-item prop="estimated_time_of_arrival">
						<template #label><span class="required-icon">*</span>预计到达</template>
						<cl-select-date v-model="form.estimated_time_of_arrival" :mode="['year', 'month', 'date']"
							format="YYYY-MM-DD" />
					</cl-form-item>
					<!-- <cl-form-item label="相关图片（最多上传6张）" prop="pics" label-position="top">
						<cl-upload v-model="form.pics" multiple :limit="6" />
					</cl-form-item> -->
				</cl-form>
			</cl-card>

			<cl-footer border>
				<cl-button size="large" round fill @tap="clear" color="#008c8c">清空</cl-button>
				<cl-button size="large" round fill @tap="submit" :loading="loading" background-color="#008c8c"
					color="#fff">
					提交
				</cl-button>
			</cl-footer>
		</view>
	</cl-page>
</template>

<script lang="ts" setup>
	import { onMounted, reactive, ref } from "vue";
	import { useUi } from "/$/cool-ui";
	import { onPageScroll } from "@dcloudio/uni-app";
	import { useCool } from "/@/cool";
	import { onLoad } from "@dcloudio/uni-app";
	import { onHide, onShow } from "@dcloudio/uni-app";
	import { checkPhone } from '../../utils'

	const { storage } = useCool()
	onPageScroll((e) => { });

	const ui = useUi();

	const form = ref({
		owner_name: "",
		plate_number: "",
		driver_number: "",
		vehicle_model: "",
		goods: "",
		expected_departure_time: "",
		estimated_time_of_arrival: "",
		pics: [],
		code: '',
		state: "运输中"
	});

	const rules = reactive({
		owner_name: {
			required: true,
			message: "货主名称不能为空",
		},
		goods: {
			required: true,
			message: "货品信息不能为空",
		},
		// plate_number: {
		// 	required: true,
		// 	message: "车牌号不能为空",
		// },
		// vehicle_model: {
		// 	required: true,
		// 	message: "车牌型号不能为空",
		// },
		// driver_number: {
		// 	required: true,
		// 	message: "司机号码不能为空",
		// },
		// expected_departure_time: {
		// 	required: true,
		// 	message: "预计出发时间不能为空",
		// },
		estimated_time_of_arrival: {
			required: true,
			message: "预计到达时间不能为空",
		},
	});

	const Form = ref<ClForm.Ref>();
	const db = uniCloud.importObject('cc_enter') //第一步导入云对象
	const loading = ref(false);
	const id = ref<string>("")
	const getDetail = async () => {
		const res = await db.detail(id.value)
		form.value = res.data[0] || {}
	}
	onHide(() => {
		id.value = ""
	})
	onLoad(async (query : any) => {
		id.value = query.id

		form.value = {
			owner_name: "",
			plate_number: "",
			vehicle_model: "",
			driver_number: "",
			goods: "",
			expected_departure_time: "",
			estimated_time_of_arrival: "",
			state: "运输中",
			pics: [],
			code: ''
		}
		if (id.value) {

			getDetail()
		} else {
			const scode = storage.get("code")
			if (scode !== 'admin') {
				const ccCode = uniCloud.importObject('cc_code')
				const { data } = await ccCode.code(scode)
				form.value.owner_name = data?.[0]?.owner_name || ''
			}
		}
	})

	async function submit() {
		Form.value?.validate(async (valid) => {
			if (form.value.driver_number) {
				const validate = checkPhone(Number(form.value.driver_number))
				if (!validate) {
					uni.showToast({
						title: "手机号码有误，请重填！",
						icon: "none"
					})
					return
				}
			}
			if (valid) {
				const ccCode = uniCloud.importObject('cc_code')
				const { data } = await ccCode.search({ owner_name: form.value.owner_name })
				if (!data?.length) {
					uni.showToast({
						title: "货主不存在，请找管理员先创建！",
						icon: "none"
					})
					return
				}
				const dcode = data[0]?.code
				const scode = storage.get("code")
				if (scode !== 'admin' && dcode !== scode) {
					uni.showToast({
						title: "请录入自己信息！",
						icon: "none"
					})
					return
				}
				ui.showConfirm({
					title: '再次确认', 
					message:"确认提交?",
					callback: async (action) => {
						if (action === 'cancel') {
							return
						} else {
							const code = scode === "admin" ? 'admin' : data[0]?.code || ''
							storage.set("code", code)
							loading.value = true;

							if (!id.value) {
								await db.add({ ...form.value, code });
							} else {
								await db.edit({ _id: id.value, ...form.value });
							}
							ui.showToast("提交成功");
							loading.value = false;
							form.value = {
								owner_name: "",
								plate_number: "",
								driver_number: "",
								vehicle_model: "",
								goods: "",
								expected_departure_time: "",
								estimated_time_of_arrival: "",
								pics: [],
								state: "运输中",
								code,
							}
							id.value = ''
							setTimeout(() => {
								uni.switchTab({
									url: "/pages/index/list"
								})
							}, 300)
						}
					}
				})
			}
		})
	}

	function reset() {
		Form.value?.reset();
	}

	function clear() {
		Form.value?.clear();
	}
</script>
<style scoped>
	.required-icon {
		color: red;
	}
	::deep .cl-button--primary {
		background: #008c8c !important;
	}
</style>